package com.manage.system.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.manage.system.context.DynamicDataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author liuzhao
 * @Date 2024/1/8 21:19
 * @Content
 * @Version 1.0
 */
@Configuration
public class DataSourceConfig {

    @Bean(name = "mountainDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.druid.mountain")
    public DataSource mountainDataSource() {
        return new DruidDataSource();
    }

    @Bean(name = "rcsDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.druid.rcs")
    public DataSource rcsDataSource() {
        return new DruidDataSource();
    }

    @Bean(name = "seeDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.druid.see")
    public DataSource seeDataSource() {
        return new DruidDataSource();
    }

    @Primary
    @Bean(name = "dynamicDataSource")
    public DataSource dynamicDataSource() {
        Map<Object, Object> targetDataSources = new HashMap<>();
        targetDataSources.put("mountain", mountainDataSource());
        targetDataSources.put("rcs", rcsDataSource());
        targetDataSources.put("see", seeDataSource());

        DynamicDataSource dynamicDataSource = new DynamicDataSource();
        dynamicDataSource.setTargetDataSources(targetDataSources);
        dynamicDataSource.setDefaultTargetDataSource(mountainDataSource());

        return dynamicDataSource;
    }

    /**
     * 配置@Transactional注解事务
     * @return
     */
    @Bean
    public PlatformTransactionManager transactionManager() {
        return new DataSourceTransactionManager(dynamicDataSource());
    }
}
